package com.dh.convert.rule.function;

import com.alibaba.fastjson.util.TypeUtils;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorRuntimeJavaType;
import com.googlecode.aviator.runtime.type.AviatorString;
import com.googlecode.aviator.runtime.type.AviatorType;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.Map;

/**
 * StringUtils.defaultIfBlank同作用
 *
 * @author huwenxuan
 * @date 2018/11/9
 */
public class DefaultIfBlankFunction extends AbstractFunction {
    @Override
    public String getName() {
        return "defaultIfBlank";
    }

    /**
     * 可指定默认值
     *
     * @param env
     * @param arg1
     * @param arg2
     * @return
     */
    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {
        //FunctionUtils#getStringValue(arg, env) 遇到env中没有arg时会抛NPE，所以这里用arg#getValue(env)来取值
        if(AviatorType.String == arg1.getAviatorType()){
            return new AviatorRuntimeJavaType(StringUtils.defaultIfBlank(TypeUtils.castToString(arg1.getValue(env)), TypeUtils.castToString(arg2.getValue(env))));
        }
        return new AviatorRuntimeJavaType(ObjectUtils.defaultIfNull(arg1.getValue(env), arg2.getValue(env)));
    }

    /**
     * 默认值为空字符串
     *
     * @param env
     * @param arg1
     * @return
     */
    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1) {
        return call(env, arg1, new AviatorString(""));
    }
}
